import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';
import 'package:flutter_media_gallery_saver/flutter_media_gallery_saver.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '保存到相册',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _globalKey = GlobalKey();
  int index = 0;
  late Timer timer;

  var progress = '0';

  @override
  void initState() {
    super.initState();
    _requestPermission();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        index++;
      });
    });
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
    _toastInfo(info);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Save to gallery"),
      ),
      body: Center(
        child: Column(
          children: [
            RepaintBoundary(
              key: _globalKey,
              child: Container(
                width: 200,
                height: 200,
                color: Colors.red,
                child: Center(
                  child: Text('$index'),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _getHttp,
                child: Text("保存网络图片"),
              ),
              width: 200,
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _saveGif,
                child: Text("保存GIF"),
              ),
              width: 200,
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _saveVideo,
                child: Text("保存视频"),
              ),
              width: 200,
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _saveLargerVideo,
                child: Text("保存大视频--$progress"),
              ),
              width: 200,
            ),
          ],
        ),
      ),
    );
  }

  _getHttp() async {
    var response = await Dio().get(
        "https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg",
        options: Options(responseType: ResponseType.bytes));
    final result = await FlutterGallerySaver.saveImage(
        Uint8List.fromList(response.data),
        quality: 60,
        name: "hello");
    print(result);
    _toastInfo("$result");
  }

  _saveGif() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.gif";
    String fileUrl =
        "https://hyjdoc.oss-cn-beijing.aliyuncs.com/hyj-doc-flutter-demo-run.gif";
    await Dio().download(fileUrl, savePath);
    final result = await FlutterGallerySaver.saveImageWithUrl(savePath);
    print(result);
    _toastInfo("$result");
  }

  _saveVideo() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    if(File(savePath).existsSync()){
      final result = await FlutterGallerySaver.saveVideo(savePath);
      print(result);
      _toastInfo("$result");
    }else{
      String fileUrl =
          "https://v-cdn.zjol.com.cn/276982.mp4";
      await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
        print((count / total * 100).toStringAsFixed(0) + "%");
      });
      final result = await FlutterGallerySaver.saveVideo(savePath);
      print(result);
      _toastInfo("$result");
    }
  }

  _saveLargerVideo() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/larger_temp.mp4";
    if(File(savePath).existsSync()){
      print("开始保存: ${DateTime.now().millisecondsSinceEpoch}");
      final result = await FlutterGallerySaver.saveVideo(savePath);
      print("保存结束: ${DateTime.now().millisecondsSinceEpoch}");
      print(result);
      _toastInfo("$result");
    }else{
      String fileUrl =
          "http://v.hbang.com.cn/d/11fc628d-8d4a-4153-8c0f-0ee6072ca40e.mp4";
      await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
        setState(() {
          progress = (count / total * 100).toStringAsFixed(0) + "%";
        });
        print((count / total * 100).toStringAsFixed(0) + "%");
      });
      final result = await FlutterGallerySaver.saveVideo(savePath);
      print(result);
      _toastInfo("$result");
    }
  }

  _toastInfo(String info) {
    Fluttertoast.showToast(msg: info, toastLength: Toast.LENGTH_LONG);
  }
}


